import React, {useEffect, useState, useRef} from 'react'
import {Button, Tag, message} from 'antd'

import {connect} from 'umi'
import moment from 'moment'
import 'moment/locale/zh-cn'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {getChannelRewardsList} from '@/service/marketing/channeRewards'
import {getAllChannelType} from '@/service/merchantCenter/rewardDetails'
// import {primaryChannelType} from '../../../dict'

const formItemLayout = {
	labelCol: {flex: '110px'},
	wrapperCol: {flex: '1'},
}

const channelRelation = (props: any) => {
	const {data, row, callBack, onlyCode} = props
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [checkData, setCheckData] = useState<any>([])

	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [dataSourse, setDataSourse] = useState<any>()
	const [primaryChannelType, setPrimaryChannelType] = useState<any[]>([])

	// 获取表格数据
	const onListFun = () => {
		callBack(row?.rentChannelVOList)
		setLoading(true)
		getChannelRewardsList({
			...params,
			...searchData,
			status: '1',
			isValid: '1',
			commodityTypeNo: onlyCode,
			subject: data?.subjectId,
			cityId: data?.city[1],
			orgId: data?.affiliatedCompanyId,
			brand: data?.brandId,
			orderType: data?.rentTypeId,
			startDate: moment(data?.beginTime).format('YYYY-MM-DD'),
			leaseTerm: row?.leaseTerm,
		})
			.then((res: any) => {
				if (res?.success) {
					const ids = row?.rentChannelVOList?.map(
						(item: any) => item?.activityCode,
					)
					const l = res?.data?.records?.map((item: any) => {
						const newItem = item
						if (ids?.includes(newItem?.channelNo)) {
							newItem.isSelect = true
						}
						newItem.activityCode = newItem?.channelNo
							? newItem?.channelNo
							: newItem.activityCode
						newItem.activityName = newItem?.name
							? newItem?.name
							: newItem.activityName
						newItem.beginTime = newItem?.startDate
							? newItem?.startDate
							: newItem.beginTime
						newItem.endTime = newItem?.endTime
							? item?.endTime
							: item?.endDate
						newItem.status = newItem?.status
							? newItem?.status
							: newItem?.auditStatus

						return newItem
					})
					setDataSourse(() => l)
					setTotal(() => res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 初始化渠道类型
	const getChannelTypeFun = () => {
		getAllChannelType()
			.then((res: any) => {
				if (res?.success) {
					setPrimaryChannelType(() => res?.data)
				}
			})
			.catch((error: any) => {
				message.error(error)
			})
	}

	useEffect(() => {
		getChannelTypeFun()
	}, [])

	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	useEffect(() => {
		setCheckData(() => row?.rentChannelVOList)
	}, [row])

	// 数据勾选
	const editCar = (record: any, type: string) => {
		if (type === 'add') {
			const userData = dataSourse?.map((item: any) => {
				const newItem = item
				if (Number(newItem.id) === Number(record?.id)) {
					newItem.isSelect = true
				}
				return newItem
			})

			setDataSourse(() => userData)
			const newData = checkData || []
			newData.push(record)
			setCheckData(() => newData)
			callBack(newData)
		} else {
			const userDataE = dataSourse?.map((item: any) => {
				const newItem = item
				if (Number(newItem.id) === Number(record?.id)) {
					newItem.isSelect = false
				}
				return newItem
			})
			setDataSourse(() => userDataE)
			const l = checkData?.filter(
				(item: any) =>
					Number(item?.awardCode || item?.id) !== Number(record?.id),
			)
			setCheckData(() => l)
			callBack(l)
		}
	}
	const columns: any = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '渠道奖励编号',
			dataIndex: 'channelNo',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '活动名称',
			dataIndex: 'name',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '渠道类型-一级',
			dataIndex: 'channelTypeOneStr',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '渠道类型-二级',
			dataIndex: 'channelTypeTwoStr',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '审核状态',
			dataIndex: 'statusStr',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? <Tag color="processing">{text}</Tag> : '--'}</>
			),
		},
		{
			title: '开始时间',
			dataIndex: 'startDate',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '结束时间',
			dataIndex: 'endDate',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '主体',
			dataIndex: 'subjectName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 250,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '所属公司',
			dataIndex: 'orgName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '品牌/车型/车系',
			dataIndex: 'brandStr',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '租期',
			dataIndex: 'leaseTerm',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (_: any, record: any) => (
				<>
					{record?.isSelect ? (
						<Button
							type="link"
							onClick={() => editCar(record, 'cancel')}>
							取消
						</Button>
					) : (
						<Button
							type="link"
							onClick={() => editCar(record, 'add')}>
							选择
						</Button>
					)}
				</>
			),
		},
	]

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])

	// 搜索
	const onFinish = (values: any) => {
		const search = {
			...values,
			channelTypeOne: values?.channelType ? values?.channelType[0] : '',
			channelTypeTwo: values?.channelType ? values?.channelType[1] : '',
		}
		setSearchData(search)
	}

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						label: '渠道奖励编号',
						name: 'channelNo',
						key: 'channelNo',
					},
					{
						type: 'input',
						label: '活动名称',
						name: 'name',
						key: 'name',
					},
					{
						type: 'cascader',
						label: '渠道类型',
						name: 'channelType',
						key: 'channelType',
						fieldNames: {
							label: 'valueName',
							value: 'value',
							children: 'secondChannelType',
						},
						items: [...primaryChannelType],
					},
				],
			},
		]
		setFormData(formItems)
	}, [primaryChannelType])

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(channelRelation)
